<?php
/**
 * Created by PhpStorm.
 * User: wudiying
 * Date: 2020/2/18
 * Time: 上午12:19
 */

/**
 * swoole进程队列通信
 *
 * string swoole_process->pop(int $maxsize=8192);//取数据
 * bool swoole_process->push(string $data);//放数据
 * array swoole_process::wait(bool $blocking=true);
 */


//示例：
$workers = [];//进程仓库
$worker_num = 2;//最大进程数


// 批量创建进程
for ($i = 0; $i < $worker_num; $i++) {
    $process = new swoole_process('doProcess', false, false);//创建新进程 想要进程间通信 必须 第三个是false
    $process->useQueue();//开启队列，类似于全局函数
    $pid = $process->start();//启动进程并获取进程id
    $workers[$pid] = $process;//放入数组
}

//进程调用的执行函数
function doProcess(swoole_process $process)
{
    $recv = $process->pop();//默认8192长度
    echo "从主进程获取导数据：$recv \n";
    sleep(5);
    $process->exit(0);
}

//主进程向子进程添加数据
foreach ($workers as $pid => $process) {
    $process->push("hello 子进程 $pid");
}

//等待子进程结束，回收资源
for ($i = 0; $i < $worker_num; $i++) {
    $ret = swoole_process::wait();//等待执行完成
    $pid = $ret['pid'];
    unset($workers[$pid]);
    echo "子进程  $pid - 退出";
}